package com.sais.manage.boot.platform.acpect;

import com.sais.manage.boot.platform.exception.ThrottleException;
import com.sais.manage.boot.platform.storage.ThrottleCodeStorage;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class ThrottleAcpect {


    @Pointcut("@annotation(com.sais.manage.boot.platform.annotation.Throttle)")
    public void throttle() {
    }

    @Before("throttle()")
    public void doLoginBefore(JoinPoint joinPoint) {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String sessionId = request.getSession().getId();
        String requestUrl = request.getRequestURI();
        String method = request.getMethod();
        if (ThrottleCodeStorage.hasThrottleCode(sessionId, requestUrl)) {
            throw new ThrottleException();
        }
        ThrottleCodeStorage.setThrottleCode(sessionId, requestUrl, 3L);
    }

    @AfterThrowing(pointcut = "throttle()")
    public void doLoginAfterThrowing(JoinPoint joinPoint) {
    }

    @AfterReturning(returning = "ret", pointcut = "throttle()")
    public void doLoginAfterReturning(Object ret) {
    }


}
